//
//  AddNewAddress_Vc.swift
//  Pods
//
//  Created by eme on 2017/4/1.
//
//


/*
 owner:cy
 update:2017年04月01日11:00:18
 info: 新增地址
 */
import RxSwift
import UtilCore
import CommonCore
import RickonCore
import BrandonCore

class AddNewAddress_Vc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    ///姓名
    @IBOutlet weak var name_TF: UITextField!
    
    @IBOutlet weak var name_SeperateLine_V: UIView!
    ///电话
    @IBOutlet weak var phone_TF: UITextField!
    
    @IBOutlet weak var phone_SeperateLine_V: UIView!
    ///省市区
    @IBOutlet weak var city_Label: UILabel!
    
    @IBOutlet weak var city_SeperateLine_V: UIView!
    ///详细地址
    @IBOutlet weak var detailedAddress_TextView: UITextView!
    
    @IBOutlet weak var detailedAddress_SeperateLine_V: UIView!
    ///是否设为详细地址
    @IBOutlet weak var isClicked: UIButton!
    /*----------------------------   自定义属性区域    ----------------------------*/
    
    var buttonWithEditor = UIButton(type:.custom) ///保存按钮
    ///如果addid有值则说明是修改否则是新增
    var addid:String?
    var manageVm:AddNewAddress_Vm?
    
    var  addressModel = AddressModel(json: "")!{
        didSet{
            if addressModel.addid.characters.count > 0 {
                self.updateViewByAddressModel(addressModel)
            }
        }
    }
    var didSelectedAddressModel:((_ addressModel:AddressModel) -> Void)?
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.addid == nil {
            self.title = "添加地址"
            if let user = AppData.loginedUser{
                self.addressModel.spid = user.thrid!
                self.city_Label.text = "\(user.glShop.agprovincename!)\(user.glShop.spareaname!)\(user.glShop.agareaname!)"
                self.addressModel.province = user.glShop.agprovincename!
                self.addressModel.city = user.glShop.spareaname!
                self.addressModel.area = user.glShop.agareaname!
            }
        }else{
            self.title = "编辑地址"
        }
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
    }
    /**
     app 主题 设置
     */
    override func setViewTheme(){
        
        self.name_SeperateLine_V.backgroundColor = Theme.v.separate_Line
        self.phone_SeperateLine_V.backgroundColor = Theme.v.separate_Line
        self.city_SeperateLine_V.backgroundColor = Theme.v.separate_Line
        self.detailedAddress_SeperateLine_V.backgroundColor = Theme.v.separate_Line
        self.setTheEditorButton()
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        /**
         *  初始化viewmodel
         */
        self.manageVm = AddNewAddress_Vm(
            refreshTriger:rx
                .sentMessage(#selector(AddNewAddress_Vc.viewWillAppear))
                .filter{ _ in self.addid != nil }
                .map{ _ in self.addid!}
        )
        self.manageVm?
            .addressModel
            .subscribe(onNext: {[unowned self](model) in
                self.addressModel = model
            })
            .disposed(by: disposeBag)
        self.manageVm?
            .error
            .bindTo(self.view.rx_error)
            .disposed(by: disposeBag)
        self.manageVm?
            .loading
            .asObservable()
            .bindTo(self.view.rx_loading)
            .disposed(by: disposeBag)
        
        self.buttonWithEditor
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                _ = self.view.endEditing(true)
                guard let name = self.name_TF.text ,name.characters.count > 0 && name.characters.count <= 15 else{
                    return self.view.toastErrorCode(100504001)
                }
                self.addressModel.recipients = name
                guard  let cellphone = self.phone_TF.text , cellphone =~ validationRegExp.mobile  else{
                    return self.view.toastErrorCode(100001001)
                }
                self.addressModel.cellphone = cellphone
                guard let address = self.detailedAddress_TextView.text , address.characters.count >= 5 , address.characters.count <= 120 else{
                    return self.view.toastErrorCode(100504002)
                }
                self.addressModel.adress = address
                self.manageVm?.changeMessage.onNext(JSONHelper.parseToJson(self.addressModel.dictionaryRepresentation() as AnyObject) as String)
            })
            .disposed(by: disposeBag)
        self.manageVm?
            .addressModelList_Success
            .subscribe(onNext: {[unowned self](list) in
                if list.count > 0{
                    if self.addid == nil{
                        self.view.toastCompletion("添加成功"){ _ in
                            self.didSelectedAddressModel?(list[0])
                            _ = self.navigationController?.popViewController(animated: true)
                        }
                    }else{
                        self.view.toastCompletion("修改成功"){ _ in
                            _ = self.navigationController?.popViewController(animated: true)
                        }
                    }
                }
                
                
            })
            .disposed(by: disposeBag)
        
        self.isClicked
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                self.isClicked.isSelected = !self.isClicked.isSelected
                self.addressModel.flag = self.isClicked.isSelected ? "0" : "1"
            })
            .disposed(by: disposeBag)
        
    }
}

extension AddNewAddress_Vc{
    func updateViewByAddressModel(_ data :AddressModel){
        self.name_TF.text = data.recipients
        self.phone_TF.text = data.cellphone
        self.detailedAddress_TextView.text = data.adress
        self.city_Label.text = data.province + data.city + data.area
        self.isClicked.isSelected = data.flag == "0"
    }
    func setTheEditorButton(){
        buttonWithEditor.frame = CGRect(x:0,y:0,width: 30,height: 15)
        buttonWithEditor.setTitleColor(UIColor.black, for: .normal)
        buttonWithEditor.titleLabel?.font = UIFont.init(name: "Helvetica Neue", size: 15)
        buttonWithEditor.setTitle("保存", for: .normal)
        let editorButton = UIBarButtonItem(customView: buttonWithEditor)
        self.navigationItem.rightBarButtonItem = editorButton
        
    }
}
